<?php

namespace App\Http\Controllers;

use App\Book;
use App\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CategoryController extends Controller
{
    // 保存
    public function save(Request $request) {
        // 检查分类名是否已经存在
        if (Category::query()->where('name', $request->get('name'))->first()) {
            return response()->json(['code' => '400', 'msg' => '分类名已存在']);
        }
        $data = $request->all();
        $category = Category::query()->find($request->get('id'));
        if ($category) {
            $category->update($data);
            return response()->json(['code' => '200', 'msg' => '更新成功']);
        }
        Category::query()->create($data);
        return response()->json(['code' => '200', 'msg' => '插入成功']);
    }

    // 删除（根据ID）
    public function delete(Request $request) {
        $id = $request->get('id');
        Category::destroy($id);
        return response()->json(['code' => '200', 'msg' => '删除成功']);
    }

    // 查询全部
    public function list() {
        $res = Category::query()->get();
        return response()->json(['code' => '200', 'msg' => '获取成功', 'data' => $res]);
    }

    // 查询单个（根据ID）
    public function one(Request $request) {
        $res = Category::query()->find($request->get('id'));
        return response()->json(['code' => '200', 'msg' => '获取成功', 'data' => $res]);
    }

    // 查询全部图书分类
    public function category() {
        $categoryParentList = Category::query()->where('isParent', '1')->get();
        $categoryInfoList = array();
        foreach ($categoryParentList as $item) {
            $categoryInfo = $item;
            $category = Category::query()->where('parentId', $item->id)->get();
            $categoryInfo->children = $category;
            array_push($categoryInfoList, $categoryInfo);
        }
        return response()->json(['code' => '200', 'msg' => '获取成功', 'data' => $categoryInfoList]);
    }

}
